const ProductModel = require('../models/product.model');
const { ValidationError } = require('../middleware/error');

class ProductController {
  // 获取商品列表
  static async getProducts(req, res, next) {
    try {
      const {
        page = 1,
        limit = 12,
        category_id,
        category_slug,
        search,
        sort_by = 'created_at',
        sort_order = 'desc',
        is_recommended
      } = req.query;

      // 验证分页参数
      const pageNum = parseInt(page);
      const limitNum = parseInt(limit);
      if (isNaN(pageNum) || pageNum < 1) {
        throw new ValidationError('参数错误', {
          page: ['页码必须是大于0的整数']
        });
      }
      if (isNaN(limitNum) || limitNum < 1 || limitNum > 50) {
        throw new ValidationError('参数错误', {
          limit: ['每页数量必须是1-50之间的整数']
        });
      }

      // 验证分类ID
      if (category_id && isNaN(parseInt(category_id))) {
        throw new ValidationError('参数错误', {
          category_id: ['分类ID必须是整数']
        });
      }

      // 处理推荐商品参数
      let isRecommended = null;
      if (is_recommended !== undefined) {
        isRecommended = is_recommended === 'true' || is_recommended === '1';
      }

      const result = await ProductModel.findAll({
        page: pageNum,
        limit: limitNum,
        category_id: category_id ? parseInt(category_id) : null,
        category_slug,
        search,
        sort_by,
        sort_order,
        is_recommended: isRecommended
      });

      // 构建分页链接
      const baseUrl = `${req.protocol}://${req.get('host')}${req.path}`;
      const queryParams = new URLSearchParams(req.query);
      
      const buildPageUrl = (pageNum) => {
        queryParams.set('page', pageNum);
        return `${baseUrl}?${queryParams.toString()}`;
      };

      res.json({
        data: result.items,
        links: {
          first: buildPageUrl(1),
          last: buildPageUrl(result.pagination.total_pages),
          prev: result.pagination.page > 1 ? buildPageUrl(result.pagination.page - 1) : null,
          next: result.pagination.page < result.pagination.total_pages ? buildPageUrl(result.pagination.page + 1) : null
        },
        meta: {
          current_page: result.pagination.page,
          from: (result.pagination.page - 1) * result.pagination.limit + 1,
          last_page: result.pagination.total_pages,
          path: baseUrl,
          per_page: result.pagination.limit,
          to: Math.min(result.pagination.page * result.pagination.limit, result.pagination.total),
          total: result.pagination.total
        }
      });
    } catch (error) {
      next(error);
    }
  }

  // 获取单个商品详情
  static async getProduct(req, res, next) {
    try {
      const { id_or_slug } = req.params;
      const product = await ProductModel.findOne(id_or_slug);
      
      res.json({
        data: product
      });
    } catch (error) {
      next(error);
    }
  }
}

module.exports = ProductController; 